package com.jie.crm.config;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import spring.data.jpa.config.EnableSimpleJpaRepositories;
import spring.data.jpa.repository.factory.SimpleJpaRepositoryFactoryBean;

/**
 * 
 * <br>
 * 时间： 2018年2月27日 下午9:52:56
 * 
 * @author wangjie
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", repositoryFactoryBeanClass = SimpleJpaRepositoryFactoryBean.class, basePackages = { "com.jie.crm.repository" })
@EnableSimpleJpaRepositories(basePackages = { "com.jie.crm" })
public class DataJpaConfig {
	@Autowired
	@Qualifier("dataSource")
	private DataSource dataSource;
	@Autowired
	private JpaProperties jpaProperties;

	@Primary
	@Bean(name = "entityManager")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactory(builder).getObject().createEntityManager();
	}

	@Primary
	@Bean(name = "entityManagerFactory")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(dataSource).properties(getVendorProperties()).packages("com.jie.crm.domain")
				.persistenceUnit("primaryPersistenceUnit").build();
	}

	private Map<String, Object> getVendorProperties() {
		return jpaProperties.getHibernateProperties(new HibernateSettings());
	}

	@Primary
	@Bean(name = "transactionManager")
	public PlatformTransactionManager transactionManagerSbf(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactory(builder).getObject());
	}

}
